package multi_thread.basic;

/**
 * @author Cheng Jun
 * Description: 通过设置线程子类或实现类的 线程终止变量 来退出线程
 * @version 1.0
 * @date 2021/9/9 20:54
 */
public class ThreadExit {
    public static void main(String[] args) throws InterruptedException {
        Exit exitRunnable = new Exit();
        Thread thread = new Thread(exitRunnable, "演示变量控制线程退出");
        thread.start();
        Thread.sleep(4000);

        // JVM进程退出
        Runtime.getRuntime().exit(1);
        // 改变 线程终止标识的变量
        // exitRunnable.setFlag(false);
        // Thread.sleep(1000);
        // Thread.State state = thread.getState();
        // String name = state.name();
        // System.out.println(name);
    }
}

class Exit implements Runnable {
    private int num = 0;
    // 线程 终止标识的变量
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "++++++" + ++num);
        }
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}